//
//  SegmentView.m
//  Mtime
//
//  Created by Mac on 15/8/3.
//  Copyright (c) 2015年 wxk. All rights reserved.
//

#import "SegmentView.h"

@implementation SegmentView
{

    float width;//每个按钮的宽度
    
    UIImageView *_selectImage;
}

- (void)addBlcok:(SegBlock)block {

    //给block赋值
    _segBlock = block;

}

//创建滑块
- (void)setSelectImageName:(NSString *)selectImageName {

    _selectImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.frame.size.height -3, width, 3)];
    
    _selectImage.image = [UIImage imageNamed:selectImageName];
    
    [self addSubview:_selectImage];

}

- (id)initWithFrame:(CGRect)frame WithTitiles:(NSArray *)titles {

    if (self = [super initWithFrame:frame]) {
        
        [self creatSegButtonItem:titles];
        
    }

    return self;
}

- (void)setTitles:(NSArray *)titles {

    _titles = titles;

    [self creatSegButtonItem:titles];
    
}

- (void)setSelectedIndex:(int)selectedIndex {

    _selectedIndex = selectedIndex;
    
    UIButton *btn = (UIButton *)[self viewWithTag:10000+selectedIndex];
    
    [self segButtonAction:btn];
}

- (void)creatSegButtonItem:(NSArray *)titles {

    width = self.frame.size.width/titles.count;
    
//    for (int i = 0; <#condition#>; <#increment#>) {
//        <#statements#>
//    }
    
    int i = 0;
    for (NSString *title in titles) {
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(i * width, 0, width, self.frame.size.height);
        
        [btn setTitle:title forState:UIControlStateNormal];
        
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
        
        btn.titleLabel.font = [UIFont boldSystemFontOfSize:20];
        
        [btn addTarget:self action:@selector(segButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        
        [btn setTag:10000 +i];
        
        [self addSubview:btn];
        
        if (i == 0) {
            
            btn.selected = YES;
            
            btn.titleLabel.font = [UIFont boldSystemFontOfSize:24];
        }
        
        i ++;
    }
}

- (void)segButtonAction:(UIButton *)sender {
 
    if (_segBlock) {
    
        _segBlock(sender.tag -10000);
    }
    
    for (UIView *view in self.subviews) {
        
        if ([view isKindOfClass:[UIButton class]]) {
            
            UIButton *btn = (UIButton *)view;
            
            btn.selected = NO;
            
            btn.titleLabel.font = [UIFont boldSystemFontOfSize:20];
            
        }
    }
    
    sender.selected = YES;//改变选中的按钮的字体颜色
    sender.titleLabel.font = [UIFont boldSystemFontOfSize:24];//改变选中的按钮的字体大小
    
    //选中滑块动画
    [UIView animateWithDuration:.2 animations:^{
       
        _selectImage.transform = CGAffineTransformMakeTranslation(width *(sender.tag -10000), 0);
        
    }];
    
}



@end
